package microcredit.model.bo;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import microcredit.model.Report;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
import org.eclipse.persistence.sessions.Session;

public class BOReport extends BOBase {

	private List<Report> reports;
	
	private void loadReports() {
		Reports reportsObject = JAXB.unmarshal(new File("./reports/reports.xml"), Reports.class);
		List<Report> reports = reportsObject.getReports();
		for (Report report : reports) {
			String fileName = report.getFile();
			File file = new File("./reports", fileName);
			if (file.exists()) {
				report.setJasperFile(file);
			}
		}
		this.reports = reports;
	}

	
	public JasperPrint run(Report report, Map<String, Object> parameters) throws Exception{

		JasperPrint print = null;
		open();
		try {
		    Session session = ((EntityManagerImpl)manager).getServerSession();
		    
		    UnitOfWorkImpl uow = (UnitOfWorkImpl)session.acquireUnitOfWork();

		    DatabaseAccessor dbAcc =(DatabaseAccessor)uow.getAccessor(); 

		    Connection connUOW = dbAcc.getConnection();

			print = JasperFillManager.fillReport(report.getJasperFile().getPath(), parameters, connUOW);
		} finally {
			close();
		}
		return print;
	}
	
	
	public List<Report> getReports() {
		if (reports == null) {
			loadReports();
		}
		return reports;
	}
	
	
	public static BOReport create() {
		return new BOReport();
	}
	
	@XmlRootElement(name="reports")
	public static class Reports {
		
		private List<Report> reports;
		
		@XmlElement(name="report")
		public List<Report> getReports() {
			return reports;
		}
		
		public void setReports(List<Report> reports) {
			this.reports = reports;
		}
		
	}
	
}
